# coding=utf-8

import time
import tornado.ioloop
import tornado.web
from tornado.options import define, options

import jspider.douban.handler.home
from jspider.config import IMG_PATH

define("debug", default="False")
define("cmd", default="")


application = tornado.web.Application([
    (r'/img/(.*)', tornado.web.StaticFileHandler, {'path': IMG_PATH}),
    (r"/douban/", jspider.douban.handler.home.HomeHanlder),
], template_path="./jspider/template/", debug=options.debug)

if __name__ == "__main__":

    options.parse_config_file("./jspider/config.py")
    options.parse_command_line()

    if options.cmd == "run_web":
        application.listen(9000)
        tornado.ioloop.IOLoop.current().start()

    elif options.cmd == "init_db":
        from jspider.douban.model.img import Img
        from jspider.douban.model.topic import Topic

        Img.create_table()
        Topic.create_table()

    elif options.cmd == "worker":
        from jspider.douban.worker import DoubanWorker
        from jspider.config import DOUBAN_GROUPS

        while 1:
            time.sleep(1)
            for group_name in DOUBAN_GROUPS:
                worker = DoubanWorker(group_name)
                worker.start()

    elif options.cmd == "worker_album":
        from jspider.douban.album_worker import AlbumWorker
        from jspider.config import ALBUMS

        while 1:
            for album_id in ALBUMS:
                print album_id
                worker = AlbumWorker(album_id)
                worker.start()
		print 1024

    else:
        print "..."
